﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using popLib;
using System.Collections;
using PhotoMgr.src.database;
using PhotoMgr.src.common;
using System.IO;

namespace PhotoMgr.src.gui.contest
{
    public partial class RoundDetail : Form
    {
        public bool NhanDoi { get; set; }
        public bool ThemMoi { get; set; }

        public int ID { get; set; }

        public int IDNhanDoi { get; set; }

        public bool inDGV { get; set; }

        public Round Record { get; set; }

        public FormAction Action { get; set; }

        public FormValidation FormValidator { get; set; }

        //public List<System.Drawing.Image> DataSource;
        public List<database.RoundImage> DataSource;

        public bool UpdateMode { get; set; }

        public bool IsDatabaseChanged { get; set; }

        public string FormTitle { get; set; }

        public RoundDetail(FormAction action, object id)
        {
            InitializeComponent();

            Action = action;

            ID = NumberLib.getInt(id);

            UpdateMode = true;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        public RoundDetail(FormAction action, int id)
        {
            InitializeComponent();

            Action = action;

            ID = id;

            UpdateMode = true;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        public RoundDetail(FormAction action)
        {
            InitializeComponent();

            Action = action;

            UpdateMode = false;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        #region Event Functions
        private void Round_Load(object sender, EventArgs e)
        {
            FormLoad();
        }
        private void btn_add_Click(object sender, EventArgs e)
        {
            ButtonAdd();
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            ButtonUpdate();
        }

        private void btn_dispose_Click(object sender, EventArgs e)
        {
            ButtonDispose();
        }

        private void btn_confirm_Click(object sender, EventArgs e)
        {
            ButtonConfirm();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            ButtonSave();
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            ButtonCancel();
        }

        private void ToaThuoc_Detail_Load(object sender, EventArgs e)
        {
            FormLoad();
        }

        private void btn_print_Click(object sender, EventArgs e)
        {
            ButtonPrint();
        }
        #endregion

        enum RoundEnum { STT, ImageTitle, Category, Artist, CategoryID, ArtistID, ImageID, RoundImageID };

        #region Handle Functions
        public virtual void FormLoad()
        {
            //init default value here
            FormTitle = "Thông tin chi tiết vòng loại";

            DataSource = new List<database.RoundImage>();

            dgv_list.AutoGenerateColumns = false;
            Global.InitDataGridView(dgv_list, new DataGridViewColumn[] { 
                Global.GenColumn("STT").SetAlign(DataGridViewContentAlignment.MiddleCenter).SetFrozen(true),//.SetVisible(false),
                Global.GenColumn("Tên hình ảnh",                    "ImageTitle").SetForeColor(Color.Blue).SetSizeMode(DataGridViewAutoSizeColumnMode.Fill).SetReadOnly(true),
                Global.GenColumn("Thể loại",                        "Category").SetReadOnly(true),
                Global.GenColumn("Người dự thi",                    "Artist").SetReadOnly(true),
                Global.GenColumn("Thể Loại ID",                     "CategoryID").SetVisible(false),
                Global.GenColumn("Người dự thi ID",                 "ArtistID").SetVisible(false),
                Global.GenColumn("Hình ảnh ID",                     "ImageID").SetVisible(false),
                Global.GenColumn("Round Image ID",                  "RoundImageID").SetVisible(false),
                Global.GenColumn("Điểm",                            "Score").SetReadOnly(true).SetAlign(DataGridViewContentAlignment.MiddleCenter),
                Global.GenColumn("Điểm phụ",                        "SubScore").SetReadOnly(true).SetAlign(DataGridViewContentAlignment.MiddleCenter),
                });

            //init default data
            Global.InitStatusCombobox(Status, Global.StatusType.Status, false);

            //DBManager.Fill....

            InitFormValidation();
            ViewDetail();

            UpdateFormAction();
            FillData();

            dgv_list.AllowUserToResizeColumns = true;
            dgv_list.AllowUserToResizeRows = false;
            dgv_list.MultiSelect = false;

            if (NhanDoi)
            {
                ButtonCopy(IDNhanDoi);
                Search(1, IDNhanDoi);
            }
            else
            {
                Search(1);
            }

            if (ThemMoi)
            {
                ThemDuLieu();
                ThemMoi = false;
            }

            ThayDoiKichThuoc();
        }

        public virtual void ButtonUpdate()
        {
            FormValidator.ChangeState(FormValidation.FormState.UpdateCurrent);

            //Not allow to Add or Delete Rows
            //dgv_list.AllowUserToAddRows = true;
            //dgv_list.AllowUserToDeleteRows = true;
        }

        public virtual void ButtonDispose() {
            ReturnSet rs = Global.FormMessage(Global.FormMessageType.ConfirmDispose, new string[] { "thông tin vòng thi", txVongThi.Text });
            if (rs.Success)
            {
                LyDoHuy.Text = rs.Message;
                NguoiHuy.Text = UserAccount.Instance.Username;
                //string currentTinhTrang = TinhTrang.SelectedValue.ToString();

                //TinhTrang.SelectedValue = "H";

                ButtonSave();

                if (FormValidator.IsFormValidated)
                {
                    ViewDetail();

                    UpdateFormAction();
                }
                else
                {
                    //TinhTrang.SelectedValue = currentTinhTrang;
                }
            }
        }

        public virtual void ButtonAdd()
        {
            //change mode and hide all buttons
            btn_update.Visible = false;
            btn_add.Visible = false;
            btn_dispose.Visible = false;
            btn_confirm.Visible = true;
            UpdateMode = false;

            Record = new Round();
            dgv_list.Rows.Clear();

            Record.Status = "O";
            //TinhTrang.SelectedValue = "M";

            FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            //set default value in form
            DataSource.Clear();

            dgv_list.Rows.Clear();

            //NgayCapNhat.Text = Global.GetServerDateTime().ToString();
            //NguoiCapNhat.Text = UserAccount.Instance.Username;
        }

        public void ThemDuLieu()
        {
        }

        public virtual void ButtonConfirm() 
        {
            if (Global.FormMessage(Global.FormMessageType.ConfirmAccept, new string[] { "Thông tin toa thuốc", txVongThi.Text }).Success)
            {
                //Stat.SelectedValue = "XN";

                ButtonSave();

                ViewDetail();

                UpdateFormAction();

                dgv_list.AllowUserToAddRows = false;
            }
        }

        public virtual void ButtonCancel()
        {
            if (UpdateMode)
            {
                FillData();
                Search(1);
                FormValidator.ChangeState(FormValidation.FormState.Ready);
            }
            else
            {
                this.Close();
            }
        }

        public void ExecuteViewDetail(object ID)
        {
            if (FormValidator.CurrentFormState == FormValidation.FormState.Ready)
            {
                this.ID = NumberLib.getInt(ID);

                UpdateMode = true;

                ViewDetail();

                UpdateFormAction();
            }
            else
            {
                FormLib.alert("Bạn đang cập nhật/thêm mới thông tin!!\r\nXin vui lòng hoàn tất trước khi xem chứng từ khác.", "Thông báo");
            }
        }

        //private bool IsDuplicateRecord()
        //{
        //    ReturnSet rs = DBManager.KeToan_CheckExistedBienPhi(TenDichVu.Text);
        //    if (rs.Success)
        //    {
        //        FormLib.alert("Thông tin biến phí " + TenDichVu.Text + " đã được tạo bởi [" + rs.Result + "]!!\r\nXin vui lòng XÁC NHẬN hoặc HỦY chứng từ cũ trước khi tạo chứng từ mới.", "Thông báo");
        //        return true;
        //    }
        //    return false;
        //}

        public virtual void ButtonSave()
        {
            if (!StringLib.isValid(txSoLuong.Text))
                return;
            if (!FormValidator.Validate())
                return;
            //if (!UpdateMode && IsDuplicateRecord())
            //    return;

            Round current = new Round();

            current.RoundID = Record.RoundID;
            current.RoundLevel = Record.RoundLevel;
            current.RoundCapacity = NumberLib.getInt(txSoLuong.Text);
            current.ContestID = Record.ContestID;
            current.DateCreated = Record.DateCreated;
            current.Status = Record.Status;

            DataSource.Clear();
            for (int i = 0; i < dgv_list.Rows.Count; i++)
            {
                var RoundImageItem = new RoundImage();

                RoundImageItem.RoundID = current.RoundID;
                RoundImageItem.ImageID = NumberLib.getInt(dgv_list.Rows[i].Cells[(int)RoundEnum.ImageID].Value);
                RoundImageItem.RoundImageID = NumberLib.getInt(dgv_list.Rows[i].Cells[(int)RoundEnum.RoundImageID].Value);

                DataSource.Add(RoundImageItem);
            }

            ReturnSet rs = DBManager.Save_RoundImage(UpdateMode, current, Record, DataSource);

            if (rs.Success)
            {
                Record = current;
                IsDatabaseChanged = true;
                FormValidator.ChangeState(FormValidation.FormState.Ready);
                dgv_list.AllowUserToAddRows = false;

                //Testinng
                Record = DBManager.Detail_Round(Record.RoundID);
                FillData();
                Search(1);

                if (!UpdateMode)
                {
                    if (FormLib.confirm("Bạn có muốn thêm mới nữa không?", "Thông báo"))
                    {
                        ButtonAdd();
                    }
                    else
                    {
                        this.Close();
                    }
                }

                //TenDichVu.Text = Record.TenDichVu;
            }
            else
            {
                Global.FormMessageType messageType = UpdateMode ? Global.FormMessageType.UpdateFail : Global.FormMessageType.AddFail;
                Global.FormMessage(messageType, new string[] { "Thông tin biến phí", txContestName.Text }, null, (Global.DBErrorType)rs.Result);
            }
        }

        public static bool ReturnCellValue(System.Windows.Forms.DataGridView datagrid, int rows, int sothutu)
        {
            if (datagrid.Rows[rows].Cells[sothutu].Value == null)
            {
                return false;
            } else {
                if ((bool)datagrid.Rows[rows].Cells[sothutu].Value.Equals(true))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public virtual void UpdateFormAction()
        {
            //int userID = NumberLib.getInt(Record.OwnUserID);
            //String username = DBManager.GetUsername(userID);

            btn_dispose.Visible = Action.DisposeRecord;
            btn_save.Visible = Action.EditRecord || Action.AddRecord;
            //btn_add.Visible = Action.AddRecord;

            //depend on UpdateMode 
            
            btn_save.Visible = Action.EditRecord || Action.EditRecordOwner || Action.AddRecord;
            //btn_add.Visible = Action.AddRecord;

            //depend on UpdateMode 
            //if (Action.EditRecord == true) //EditRecord == true -> free to edit any record
            //    btn_update.Visible = UpdateMode && Record.TinhTrang == "M";
            //else if (Action.EditRecordOwner == true) //EditRecordOwner == true -> if NguoiTao == username -> allow to edit
            //    btn_update.Visible = UpdateMode && Record.OwnUserID == UserAccount.Instance.Username && Record.TinhTrang == "M";

            if (Action.ConfirmRecord == true) //ConfirmRecord == true -> free to confirm any record
                btn_confirm.Visible = Record.Status == "O";
            else if (Action.DisposeRecordOwner == true) //DisposeRecordOwner == true -> if NguoiTao == username -> allow to dispose
                btn_confirm.Visible = Record.Status == "O";

            if (Action.DisposeRecord == true) //DisposeRecord == true -> free to dispose any record
                btn_dispose.Visible = UpdateMode && Record.Status == "XN";
            else if (Action.DisposeRecordOwner == true) //DisposeRecordOwner == true -> if NguoiTao == username -> allow to dispose
                btn_dispose.Visible = UpdateMode  && Record.Status == "XN";

            //btn_confirm.Visible = Action.ConfirmRecord && Record.TinhTrang == "M";
            btn_confirm.Visible = Record.Status == "M";

            //btn_dispose.Visible = Action.DisposeRecord && UpdateMode && Record.TinhTrang == "XN";
            btn_dispose.Visible = UpdateMode && Record.Status == "XN";

            btn_print.Visible = UpdateMode && Record.Status == "XN";

            //update shortcutkey for button
            Global.InitDetailFormButton(this, btn_add, btn_update, btn_confirm, btn_dispose, btn_cancel, btn_save, btn_print);
        }

        public virtual void InitFormValidation()
        {
            FormValidator = new FormValidation(this);
            FormValidator.AddHandleContainer(flp_container);
            FormValidator.AddHandleControl(dgv_list);
            FormValidator.InitNavigatorForm(btn_add, btn_update, btn_dispose, btn_save, btn_cancel, btn_confirm, btn_print);
            FormValidator.FormStateChanged += new FormValidation.FormStateChangeEvent(FormStateChanged);

            //init validation here
            FormValidator.ValidateText(txVongThi, true, 1, -1);

            btn_add.Visible = false;
            //Global.InitDetailFormButton(this, btn_add, btn_update, btn_confirm, btn_dispose, btn_cancel, btn_save, btn_print);
            
            FormValidator.AddHandleControlExceptLock(Status);
            FormValidator.AddHandleControlExceptLock(txVongThi);
            FormValidator.AddHandleControlExceptLock(btn_add);
            FormValidator.AddHandleControlExceptLock(cbNgayBatDau);
            FormValidator.AddHandleControlExceptLock(cbNgayKetThuc);
            FormValidator.AddHandleControlExceptLock(cbNgayTao);
            FormValidator.AddHandleControlExceptLock(txContestName);

            this.KeyDown += delegate(object sender, KeyEventArgs e)
            {
                switch (e.KeyCode)
                {
                    case Keys.Enter:
                        if (inDGV)
                        {
                            WindowLib.PressKey(Keys.Tab);
                        }
                        break;
                }
            };
        }

        public virtual void FormStateChanged(FormValidation.FormState state)
        {
            switch (state)
            {
                default:
                case FormValidation.FormState.Ready:
                    this.Text = FormTitle;
                    break;
                case FormValidation.FormState.CreateNew:
                    this.Text = FormTitle + " - Thêm mới";
                    break;
                case FormValidation.FormState.UpdateCurrent:
                    this.Text = FormTitle + " - Cập nhật";
                    break;
            }
        }

        public virtual void ViewDetail()
        {

            if (UpdateMode)
            {
                //Bổ sung
                Round result = DBManager.Detail_Round(ID);
                Record = (Round)result;
                FillData();

                if (Record.Status != "H")
                {
                    lbLyDoHuy.Visible = lbNgayHuy.Visible = lbNguoiHuy.Visible = false;
                    gbx_cotainer.Height = 144;
                }
                else
                {
                    lbLyDoHuy.Visible = lbNgayHuy.Visible = lbNguoiHuy.Visible = true;
                    gbx_cotainer.Height = 210;
                    dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y + 75);
                    dgv_list.Height = 295;
                }
            }
            else
            {
                ButtonAdd();
            }
        }

        public virtual void ViewDetail(int NhanDoi)
        {

        }

        public virtual void FillData()
        {
            if (Record == null) return;

            if (Record.ContestID == null) return;

            txSoLuong.Text = Global.GetString(Record.RoundCapacity);

            Contest mycontest = DBManager.Detail_Contest(NumberLib.getInt(Record.ContestID));

            txContestName.Text = mycontest.ContestName;
            cbNgayBatDau.Values = (DateTime) mycontest.DateStart;
            cbNgayKetThuc.Values = (DateTime)mycontest.DateEnd;
            txVongThi.Text = Global.GetString(Record.RoundLevel);
            cbNgayTao.Values = (DateTime) mycontest.DateCreated;
            Status.SelectedValue = Record.Status;
            Search(1);

            

            //FillDetail(Record.ContestID);
        }

        public virtual void FillDetail(int Contest_ID)
        {

        }

        public virtual void Search(int page)
        {
            dgv_list.Rows.Clear();
            List<RoundImage> result = DBManager.SearchRoundImage(ID);
            //List<database.Image> result = DBManager.SearchImage(ID);

            int STT = 1;
            foreach (var item in result)
            {
                dgv_list.Rows.Add(new object[] { STT.ToString(), item.Image.ImageTitle, item.Image.Category.CategoryName, item.Image.Artist.ArtistName, item.Image.CategoryID, item.Image.ArtistID, item.ImageID, item.RoundImageID, item.Score, item.SubScore });
                STT++;
            }
        }

        public virtual void Search(int page, int SearchID)
        {
            dgv_list.Rows.Clear();
            List<RoundImage> result = DBManager.SearchRoundImage(ID);
            //List<database.Image> result = DBManager.SearchImage(ID);

            int STT = 1;
            foreach (var item in result)
            {
                dgv_list.Rows.Add(new object[] { STT.ToString(), item.Image.ImageTitle, item.Image.Category.CategoryName, item.Image.Artist.ArtistName, item.Image.CategoryID, item.Image.ArtistID, item.ImageID, item.RoundImageID, item.Score, item.SubScore });
                STT++;
            }
        }

        public virtual void ButtonPrint() 
        {
            //List<ReportData_ToaThuoc> source = new List<ReportData_ToaThuoc>();
            //foreach (DataGridViewRow row in dgv_list.Rows)
            //{
            //    if (row.Cells[0].Value != null)
            //    {
            //    }
            //}

            //using (var a = new Report_ToaThuoc(source)
            //{
            //    NgayGioIn = Global.GetServerDateTime().ToGioNgayString(),
            //    NguoiLap = UserAccount.Instance.TenNhanVien,
            //    TenBenhNhan = TenBenhNhan.Text.ToUpper(),
            //    MaToa = StringLib.Replace1time(TenDichVu.Text, "-TTRV", ""),
            //    HA = HA.Text == "-" ? "-" : HA.Text.Contains("mmHg")? HA.Text : HA.Text + "mmHg" ,
            //    TanSoTim = TanSoTim.Text == "0" ? "0" : TanSoTim.Text + " lần/phút",
            //    Tuoi = Tuoi.Text,

            //})
            //{
            //    a.ShowDialog();
            //}
        }
        #endregion

        public static bool CheckTF(double soluong)
        {
            if (soluong != 0)
            {
                return true;
            }
            else return false;
        }

        private void dgv_list_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is DataGridViewComboBoxEditingControl)
            {
                ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
                ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
                ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
            }
        }

        private void ToaThuoc_Detail_FormClosing(object sender, FormClosingEventArgs e)
        {
            FormClose(e);
        }

        public virtual void FormClose(FormClosingEventArgs e)
        {
            if (FormValidator.CurrentFormState != FormValidation.FormState.Ready)
            {
                if (!Global.FormMessage(Global.FormMessageType.ConfirmCancel, "Nhập Liệu vòng loại").Success)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void dgv_list_Enter(object sender, EventArgs e)
        {
            this.Tag = false;
            inDGV = true;
        }

        private void dgv_list_Leave(object sender, EventArgs e)
        {
            this.Tag = true;
            inDGV = false;
        }

        private void dgv_list_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13) txVongThi.Focus(); 
            {
            }
        }

        private void btn_copy_Click(object sender, EventArgs e)
        {
            ButtonCopy();
        }

        public virtual void ButtonCopy(int IDnhandoi)
        {
            //change mode and hide all buttons
            btn_update.Visible = false;
            //btn_add.Visible = false;
            btn_dispose.Visible = false;
            btn_confirm.Visible = true;

            UpdateMode = false;

            int ID_tam = IDnhandoi;
            FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            //set default value in form
            //BienPhi itemTam = DBManager.Detail_BienPhi(ID_tam);

            //TenDichVu.Text = itemTam.TenDichVu;
            //TenDichVuEHosp.Text = itemTam.TenDichVu_eHosp;
            //MaDichVu.Text = itemTam.MaDichVu;
            //NgayCapNhat.Text = itemTam.NgayCapNhat.Value.ToString();

            //String tinhtranghientai = TinhTrang.SelectedValue.ToString();
            //if (tinhtranghientai == "H")
            //{
            //    gbx_cotainer.Height = 210;

            //    dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
            //    dgv_list.Height = 295;
            //}

            //Record = new BienPhi();

            //Record.TinhTrang = "M";
            //TinhTrang.SelectedValue = "M";
        }

        public virtual void ButtonCopy()
        {
            //change mode and hide all buttons
            btn_update.Visible = false;
            //btn_add.Visible = false;
            btn_dispose.Visible = false;
            btn_confirm.Visible = true;
            UpdateMode = false;
            //Record = new KhungGiaBHYT();

            int ID_tam = this.ID;
            FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            //set default value in form

            var itemTam = DBManager.Detail_Contest(ID);

            txVongThi.Text = "";
            txVongThi.Text = itemTam.ContestName;
            //NguoiCapNhat.Text = UserAccount.Instance.Username;

            String tinhtranghientai = Status.SelectedValue.ToString();

            if (tinhtranghientai == "H")
            {
                gbx_cotainer.Height = 112;

                dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
                dgv_list.Height = 396;
            }

            Record = new Round();

            Record.Status = "M";
            Status.SelectedValue = "M";
        }

        private void btn_add_EnabledChanged(object sender, EventArgs e)
        {
            //btn_copy.Enabled = btn_add.Enabled;
        }

        public virtual void FillCopyData(int IDCopy)
        {
            this.IDNhanDoi = IDCopy;

            NhanDoi = true;
        }

        private void TinhTrang_SelectedIndexChanged(object sender, EventArgs e)
        {
            String tinhtranghientai = Status.SelectedValue.ToString();

            //if (tinhtranghientai == "M")
            //{
            //    gbx_cotainer.Height = 141;

            //    //dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
            //    dgv_list.Height = 367;
            //}

            //if (tinhtranghientai == "H")
            //{
            //    gbx_cotainer.Height = 112;

            //    dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
            //    dgv_list.Height = 396;
            //}
        }

        public void ThayDoiKichThuoc()
        {

            if (Status.SelectedValue == null) return;

            String tinhtranghientai = Status.SelectedValue.ToString();

            if (tinhtranghientai == "M")
            {
                gbx_cotainer.Height = 141;

                //dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
                dgv_list.Height = 367;
            }

            if (tinhtranghientai == "H")
            {
                gbx_cotainer.Height = 112;

                dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
                dgv_list.Height = 396;
            }
        }

        private void ThemHinh_Click(object sender, EventArgs e)
        {
            dynamic form = new Form();
            FormAction action = new FormAction(false, true, false, false, false, true);

            //form = new ImageList(action, "");
            form = new gui.Image.ImageList( "Chọn hình ảnh", action);
            form.ShowDialog();

            if (form.SelectedItem == null) return;

            foreach (View_ImageDetail item in form.SelectedList)
            {
                AddImage(item);
            }

            //object SelectedObject = form.SelectedItem;

            //string ImageID = form.SelectedID.ToString();

            //int CategoryID = NumberLib.getInt(form.SelectedItem.CategoryID.ToString());
            //int AuthorID = NumberLib.getInt(form.SelectedItem.ArtistID.ToString());

            //string ImageTitle = form.SelectedItem.ImageTitle.ToString();
            //string ImageCategory = DBManager.GetCategoryName(NumberLib.getInt(form.SelectedItem.CategoryID.ToString()));
            //string ImageAuthor = DBManager.GetArtistName(NumberLib.getInt(form.SelectedItem.ArtistID.ToString()));

            //for (int i = 0; i < dgv_list.Rows.Count; i++)
            //{
            //    if (NumberLib.getInt(dgv_list.Rows[i].Cells[(int)RoundEnum.ImageID].Value) == NumberLib.getInt(ImageID))
            //    {
            //        MessageBox.Show("Không thể thêm 1 hình 2 lần !!!","Thông báo");
            //        return;
            //    }
            //}

            //dgv_list.Rows.Add(new object[] { 0, ImageTitle, ImageCategory, ImageAuthor, CategoryID, AuthorID, ImageID, 0 });

            //SapXepDGV();
        }

        void AddImage(View_ImageDetail image)
        {

            string ImageID = image.ImageID.ToString();
            int CategoryID = (int)image.CategoryID;
            int AuthorID = (int)image.ArtistID;

            string ImageTitle = image.ImageTitle;
            string ImageCategory = image.CategoryName;
            string ImageAuthor = image.ArtistName;

            for (int i = 0; i < dgv_list.Rows.Count; i++)
            {
                if (NumberLib.getInt(dgv_list.Rows[i].Cells[(int)RoundEnum.ImageID].Value) == NumberLib.getInt(ImageID))
                {
                    MessageBox.Show("Không thể thêm 1 hình 2 lần !!!", "Thông báo");
                    return;
                }
            }

            dgv_list.Rows.Add(new object[] { 0, ImageTitle, ImageCategory, ImageAuthor, CategoryID, AuthorID, ImageID, 0, 0, 0 });

            SapXepDGV();
        }

        private void btn_save_EnabledChanged(object sender, EventArgs e)
        {
            btThemVongMoi.Enabled = btn_save.Enabled;
        }

        private void SapXepDGV()
        {
            for (int i = 0; i < dgv_list.Rows.Count; i++)
            {
                dgv_list.Rows[i].Cells[(int)RoundEnum.STT].Value = i + 1;
            }
        }

        private void btXoaHinhAnh_Click(object sender, EventArgs e)
        {
            if (dgv_list.CurrentRow != null && dgv_list.CurrentRow.Index >= 0)
            {
                dgv_list.Rows.Remove(dgv_list.CurrentRow);
            }

            SapXepDGV();
        }

        private void dgv_list_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (NumberLib.getInt(dgv_list.CurrentRow.Cells[(int)RoundEnum.ImageID].Value) == 0)
                return;

            database.Image myimage = DBManager.Detail_Image(NumberLib.getInt(dgv_list.CurrentRow.Cells[(int)RoundEnum.ImageID].Value));
            pBShowPicture.Image = System.Drawing.Image.FromFile(myimage.ImagePath);
            pBShowPicture.SizeMode = PictureBoxSizeMode.Zoom;

            GC.Collect();
        }

        private void btThemVongMoi_EnabledChanged(object sender, EventArgs e)
        {
            btXoaHinhAnh.Enabled = btThemVongMoi.Enabled;
        }

        public void updateButtonUpdate(bool allowUpdate)
        {
            btn_update.Visible = allowUpdate;
        }
    }
}

